<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 200px;margin-right: 20px">
        <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-input
        v-model="listQuery.tplName"
        :placeholder="'请输入' + tempDesc.tplName"
        style="width: 200px;margin-right: 20px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-refresh" @click="handleFilter">
        刷新
      </el-button>
      <el-button
        v-has="'newsTemplateList:add'"
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        {{ $t('table.add') }}
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column :label="tempDesc.wxAccountName">
        <template slot-scope="scope">
          <span>{{ scope.row.wxAccountName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.tplName">
        <template slot-scope="scope">
          <span>{{ scope.row.tplName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.isUpload">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isUpload == 1 ? 'success' : 'danger'" hit>
            {{ scope.row.isUpload == 1 ? '&nbsp;&nbsp;是&nbsp;&nbsp;' : '&nbsp;&nbsp;否&nbsp;&nbsp;' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="图文类型" :formatter="formatNewsType" />
      <el-table-column :label="tempDesc.countArticle">
        <template slot-scope="scope">
          <span>{{ scope.row.countArticle }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="tempDesc.isRelatedMenu" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isRelatedMenu == 1 ? 'success' : 'danger'" hit>
            {{ scope.row.isRelatedMenu == 1 ? '&nbsp;&nbsp;是&nbsp;&nbsp;' : '&nbsp;&nbsp;否&nbsp;&nbsp;' }}
          </el-tag>
        </template>
      </el-table-column>
      <!--<el-table-column :label="tempDesc.createTime" width="160px">-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.createTime }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <!--<el-table-column :label="tempDesc.updateTime" width="160px">-->
        <!--<template slot-scope="scope">-->
          <!--<span>{{ scope.row.updateTime }}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->

      <el-table-column v-if="checkBtnPermission(['newsTemplateList:edit','newsTemplateList:editnews','newsTemplateList:preview','newsTemplateList:delete'])" :label="$t('table.actions')" width="350px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-has="'newsTemplateList:edit'" type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <router-link v-has="'newsTemplateList:editnews'" :to="'/wxmpMaterialManage/newsTemplateForm/'+scope.row.id">
            <el-button type="primary" size="mini" style="width: 100px;margin-left: 10px" icon="el-icon-edit">
              编辑图文
            </el-button>
          </router-link>
          <el-button v-has="'newsTemplateList:preview'" type="success" size="mini" style="margin-left: 10px" :disabled="scope.row.isUpload == 0" icon="el-icon-view" @click="handleSendPreview(scope.row)">
            预览
          </el-button>
          <el-button v-has="'newsTemplateList:delete'" type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="tempDesc.wxAccountId" prop="wxAccountId">
          <el-select v-model="temp.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 280px;" :disabled="dialogStatus !='create'">
            <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item :label="tempDesc.tplName" prop="tplName">
          <el-input v-model="temp.tplName" :placeholder="'请输入' + tempDesc.tplName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <!--发送预览窗口-->
    <el-dialog title="发送预览" :visible.sync="dialogFormVisible2">
      <el-form
        ref="dataForm2"
        :model="temp2"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item :label="tempDesc.wxAccountId" prop="wxAccountId">
          <el-select v-model="temp2.wxAccountId" placeholder="请选择公众号" clearable class="filter-item" style="width: 280px;" :disabled="dialogStatus !='create'">
            <el-option v-for="item in accountListOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="粉丝名称">
          <el-select
            v-model="temp2.fansSelected"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入粉丝名称进行搜索"
            :remote-method="filterFans"
            :loading="loading"
            style="width: 280px"
          >
            <el-option
              v-for="item in fansOptions"
              :key="item.id"
              :label="item.nicknameStr"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancelSendPreview">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="sendDataPreview">
          发送
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkBtnPermission } from '@/utils/permission' // 权限判断函数
import { fetchList, createRow, updateRow, deleteRow, filterFans, sendNewsPreview } from '@/api/wx-news-template'
import { fetchAllAccount } from '@/api/wx-account'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

// 常量title
const tempDesc = {
  'id': '',
  'tplName': '模板名称',
  'isUpload': '是否已上传微信',
  'wxAccountId': '公众号名称',
  'createTime': '创建时间',
  'updateTime': '更新时间',
  'wxAccountName': '公众号名称',
  'countArticle': '图文数量',
  'isRelatedMenu': '是否已关联菜单'
}
export default {
  // name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        tplName: '',
        wxAccountId: ''
      },
      showReviewer: false,
      temp: {
        'id': '',
        'tplName': '',
        'isUpload': '',
        'wxAccountId': '',
        'createTime': '',
        'updateTime': '',
        'wxAccountName': '',
        'countArticle': ''
      },
      tempDesc: tempDesc,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '增加'
      },
      rules: {
        wxAccountId: [{ required: true, message: '请选择公众号', trigger: 'blur' }],
        tplName: [{ required: true, message: '请输入' + tempDesc.tplName, trigger: 'blur' }]
      },
      accountListOptions: [
      ],
      dialogFormVisible2: false,
      temp2: {
        'newsId': '',
        'wxAccountId': '',
        'fansSelected': []
      },
      fansOptions: [],
      loading: false,
      fansSelected: []
    }
  },
  created() {
    this.getList()
    this.getAccountList()
  },
  methods: {
    checkBtnPermission,
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        'id': '',
        'tplName': '',
        'isUpload': '',
        'wxAccountId': '',
        'createTime': '',
        'updateTime': '',
        'wxAccountName': ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createRow(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateRow(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      if (row.isRelatedMenu == '1') {
        this.$message({ message: '请先解除关联', type: 'warning' })
        return false
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var params = { 'id': row.id }
          deleteRow(params).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        })
    },
    getAccountList() {
      fetchAllAccount().then(response => {
        this.accountListOptions = []
        for (var i = 0; i < response.data.length; i++) {
          this.accountListOptions.push({ 'key': response.data[i].id + '', 'display_name': response.data[i].name })
        }
      })
    },
    handleUpload() {
      this.$confirm('确定上传图文到微信?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = { 'id': row.id }
        deleteRow(params).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    formatNewsType(row, column) {
      if (row.countArticle == 0) {
        return ''
      }
      if (row.countArticle == 1) {
        return '单图文'
      }
      if (row.countArticle > 1) {
        return '多图文'
      }
    },
    handleSendPreview(row) {
      this.temp2.newsId = row.id
      this.temp2.wxAccountId = row.wxAccountId
      this.temp2.fansSelected = []
      this.dialogFormVisible2 = true
      this.$nextTick(() => {
        this.$refs['dataForm2'].clearValidate()
      })
    },
    cancelSendPreview() {
      this.dialogFormVisible2 = false
      this.fansOptions = []
    },
    filterFans(value) {
      if (!value) {
        return false
      }
      this.loading = true
      var params = { 'wxAccountId': this.temp2.wxAccountId, 'nicknameStr': value }
      filterFans(params).then(res => {
        this.loading = false
        this.fansOptions = res.data
      })
    },
    sendDataPreview() {
      if (this.temp2.fansSelected.length == 0) {
        this.$message({ message: '请选择粉丝', type: 'warning' })
        return false
      }

      this.$confirm('确定发送预览图文?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = Object.assign({}, this.temp2)
        sendNewsPreview(params).then(res => {
          this.dialogFormVisible2 = false
          this.$notify({
            title: '成功',
            message: '发送成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    }
  }
}
</script>
